//
//  PaintingListViewController.swift
//  NDAi
//
//  Created by 丸子 on 2024/7/24.
//

import UIKit
import JXSegmentedView
class PaintingListViewController: UIViewController, JXSegmentedListContainerViewListDelegate {
    let viewModel = PaintingViewModel()
    let disposeBag = DisposeBag()
    let releaseViewModel = WorksViewModel()
    
    var type:Bool = false
    private lazy var collectionView: UICollectionView = {
        //        let layout = UICollectionViewFlowLayout()
        //        layout.scrollDirection = .vertical
        let layout = WaterFallFlowLayout()
        layout.delegate = self
        layout.sectionInset = UIEdgeInsets(top: 0, left: 14, bottom: 64 + bottomSafeAreaHeight, right: 14)
        // 设置每行的项目数量
        let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.register(cellWithClass: HomeDrawItemCell.self)
        collectionView.backgroundColor = UIColor.clear // 设置背景颜色
        collectionView.showsVerticalScrollIndicator = false
        collectionView.showsHorizontalScrollIndicator = false
        return collectionView
    }()
    private lazy var descGenerateBtn: UIButton = {
        let button = UIButton(type: .custom)
        button.titleForNormal = "发布"
        button.titleFont = UIFont.pingFangSCRegular(ofSize: 16)
        button.titleColorForNormal = .white
        button.allRound(27)
        button.backgroundColor = UIColor(hexString: "#25262B")
        button.isHidden = true
        return button
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.addSubview(collectionView)
        self.collectionView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        self.viewModel.getHomeDrawList()
        self.collectionView.addHeaderRefresh { [weak self] in
            guard let self = self else { return }
            self.viewModel.page = 1
            self.viewModel.getHomeDrawList()
        }
        self.collectionView.addFooterRefresh { [weak self] in
            guard let self = self else { return }
            self.viewModel.page += 1
            self.viewModel.getHomeDrawList()
        }
        self.bindEvent()
        if self.type {
            self.view.addSubview(descGenerateBtn)
            descGenerateBtn.snp.makeConstraints { make in
                make.bottom.equalTo(self.safeBottom).offset(-10)
                make.leading.trailing.equalToSuperview().inset(32)
                make.height.equalTo(54)
            }
            
            descGenerateBtn.setClosureTouchUpInside_k { [weak self] in
                self?.generate()
            }
            
            releaseViewModel.reloadListSubject.subscribe(onNext: { [weak self] in
                self?.reload()
                let vc = ReleaseViewController()
                vc.type = 1
                self?.navigationController?.pushViewController(vc)
            }).disposed(by: disposeBag)
            
            
            releaseViewModel.errorSubject.subscribe(onNext: { [weak self] in
                self?.reload()
                let vc = ReleaseViewController()
                vc.type = 2
                self?.navigationController?.pushViewController(vc)
            }).disposed(by: disposeBag)
        }
    } 
    func reload(){
        self.descGenerateBtn.isHidden = true
        for (index, value) in self.viewModel.imageList.enumerated() {
            self.viewModel.imageList[index].isSelect = false
        }
        self.collectionView.reloadData()
    }
    func generate(){
        if let model = self.viewModel.imageList.first(where: { $0.isSelect == true } ) {
            self.releaseViewModel.releaseWorks(id: model.id ?? "", type: 1)
        }else {
            NDProgressHUD.show(message: "请选择作品，在尝试发布。")
        }
    }
    func bindEvent(){
        self.viewModel.reloadDataSubject.subscribe(onNext: { [weak self] in
            self?.collectionView.endHeaderRefresh()
            self?.collectionView.endFooterRefresh()
            self?.collectionView.reloadData()
        }).disposed(by: disposeBag)
    }
    
    func listView() -> UIView {
        return self.view
    }
}
extension PaintingListViewController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, WaterFallLayoutDelegate {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.viewModel.imageList.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let model = self.viewModel.imageList[indexPath.item]
        let cell = collectionView.dequeueReusableCell(withClass: HomeDrawItemCell.self, for: indexPath)
        cell.setup(model)
        
        if self.type {
            cell.selectBtn.isHidden = false
            cell.selectBtn.isSelected = model.isSelect
            if model.isSelect {
                cell.iconIV.layer.borderWidth = 2
                cell.iconIV.layer.borderColor = UIColor(hexString: "#45DFFF").cgColor
            }else {
                cell.iconIV.layer.borderWidth = 2
                cell.iconIV.layer.borderColor = UIColor.clear.cgColor
            }
            
            cell.selectBtn.setClosureTouchUpInside_k { [weak self] in
                guard let self = self else { return }
                for (index, value) in self.viewModel.imageList.enumerated() {
                    self.viewModel.imageList[index].isSelect = false
                }
                if model.isSelect {
                    self.viewModel.imageList[indexPath.item].isSelect = false
                }else {
                    self.viewModel.imageList[indexPath.item].isSelect = true
                }
                self.collectionView.reloadData()
                checkState()
            }
        }else {
            cell.selectBtn.isHidden = true
        }
        return cell
    }
    func checkState(){
        if let model = self.viewModel.imageList.first(where: { $0.isSelect == true } ) {
            descGenerateBtn.isHidden = false
        }else {
            descGenerateBtn.isHidden = true
        }
    }
    //    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    //        let width = (SCREEN_WIDTH - 38) / 2
    //        return CGSize(width: Int(width), height: Int(width + 34))
    //    }
    //
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let model = self.viewModel.imageList[indexPath.item]
        let vc = PaintingDetailsViewController()
        vc.model = model
        self.navigationController?.pushViewController(vc)
    }
    
    
    func waterFlowLayout(_ waterFlowLayout: WaterFallFlowLayout, itemHeight indexPath: IndexPath) -> CGFloat {
        let model = self.viewModel.imageList[indexPath.item]
        if let p = model.proportion_value { // "9:16"
            let width = (SCREEN_WIDTH - 38) / 2
            let height = calculateHeight(width: width, proportion: p) ?? CGFloat(arc4random_uniform(150) + 50)
            return height + 34.0
        }
        return CGFloat(arc4random_uniform(150) + 50)
    }
    
    // 示例方法
    func calculateHeight(width: CGFloat, proportion: String) -> CGFloat? {
        // 分割比例字符串，获取宽度和高度的比率
        let components = proportion.split(separator: ":")
        guard components.count == 2,
              let widthRatio = Double(components[0]),
              let heightRatio = Double(components[1]) else {
            return nil
        }
        
        // 根据比例计算高度
        let height = width * CGFloat(heightRatio / widthRatio)
        return height
    }
}


class HomeDrawItemCell: UICollectionViewCell {
    lazy var iconIV: UIImageView = {
        let imageView = UIImageView()
        imageView.allRound(4)
        imageView.contentMode = .scaleAspectFill
        imageView.layer.masksToBounds = true
        imageView.clipsToBounds = true
        imageView.backgroundColor = UIColor(hexString: "#25262B")
        return imageView
    }()
    
    lazy var titleLb: UILabel = {
        let label = UILabel()
        //        label.backgroundColor = UIColor(hexString: "#222225", transparency: 0.9)
        label.textColor = Theme.color.text_d1
        label.font = UIFont.pingFangSCRegular(ofSize: 12)
        label.textAlignment = .center
        label.text = "唯美"
        return label
    }()
    
    lazy var selectBtn: UIButton = {
        let button = UIButton(type: .custom)
        button.imageForNormal = UIImage(named: "icon_works_nor")
        button.imageForSelected = UIImage(named: "icon_works_sel")
        button.isHidden = true
        return button
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = .clear
        contentView.addSubviews([iconIV, titleLb, selectBtn])
        contentView.backgroundColor = .white
        contentView.allRound(8)
        iconIV.snp.makeConstraints { make in
            make.top.leading.trailing.equalToSuperview()
            make.bottom.equalTo(-34)
        }
        titleLb.snp.makeConstraints { make in
            //            make.bottom.leading.trailing.equalToSuperview()
            //            make.height.equalTo(20)
            make.top.equalTo(iconIV.snp.bottom).offset(0)
            make.leading.trailing.equalToSuperview()
            make.height.equalTo(34)
        }
        
        selectBtn.snp.makeConstraints { make in
            make.bottom.equalTo(iconIV.snp.bottom).offset(-10)
            make.leading.equalTo(iconIV.snp.leading).offset(10)
        }
    }
    
    func setup(_ model:PaintImageDataModel) {
        iconIV.sd_setImage(with: URL(string: model.img_url ?? ""))
        titleLb.text = model.message?.replacingOccurrences(of: "\n", with: "")
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
